package br.praticas.projetoacademia.views;


import br.praticas.projetoacademia.dao.PlanoDao;
import br.praticas.projetoacademia.models.Plano;
import br.praticas.projetoacademia.util.Check;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**
 *
 * @author lucia
 * @see classe PlanoDao
 * @since 16\11\2014
 */
public class PlanoView extends javax.swing.JDialog {

   Plano plano = new Plano();
    PlanoDao daoPlano = new PlanoDao();
    List<Plano> listaModelPlanos = new ArrayList<>();
    String tipoCadastro;

    public PlanoView() {
        initComponents();
        setLocationRelativeTo(null);
        this.preencherTabela();

    }
  
    /**
     * Metodo que lista todos os planos em uma tabela, com seus respectivos dados.
     */
     private void preencherTabela() {
        String colunas[] = {"Tipo","Valor","Quantidade"};
        listaModelPlanos = daoPlano.listarPlanos();
        String dados[][] = new String[listaModelPlanos.size()][2];
        //CARREGA OS DADOS DA LISTA NA TABELA
        int cont = listaModelPlanos.size();
        for (int i = 0; i < cont; i++) {
            dados[i][0] = listaModelPlanos.get(i).getTipo();
            dados[i][1] = listaModelPlanos.get(i).getValor();
        }
        TableModel model = new DefaultTableModel(dados, colunas);
        tabela.setModel(model);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSpinner1 = new javax.swing.JSpinner();
        defaultTask1 = new net.sf.nachocalendar.tasks.DefaultTask();
        valor = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        Novo = new javax.swing.JButton();
        Cancelar = new javax.swing.JButton();
        Excluir = new javax.swing.JButton();
        Salvar = new javax.swing.JButton();
        Alterar = new javax.swing.JButton();
        tipo1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Plano");

        valor.setEditable(false);

        jLabel2.setText("Valor:");

        jLabel8.setText("Tipo:");

        tabela.setAutoCreateRowSorter(true);
        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Tipo", "Valor"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabela.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        tabela.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(tabela);

        Novo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/praticas/projetoacademia/imagens/Add.png"))); // NOI18N
        Novo.setText("Novo");
        Novo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NovoActionPerformed(evt);
            }
        });

        Cancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/praticas/projetoacademia/imagens/No.png"))); // NOI18N
        Cancelar.setText("Cancelar");
        Cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelarActionPerformed(evt);
            }
        });

        Excluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/praticas/projetoacademia/imagens/Delete.png"))); // NOI18N
        Excluir.setText("Excluir");
        Excluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExcluirActionPerformed(evt);
            }
        });

        Salvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/praticas/projetoacademia/imagens/Save.png"))); // NOI18N
        Salvar.setText("Salvar");
        Salvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SalvarActionPerformed(evt);
            }
        });

        Alterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/praticas/projetoacademia/imagens/Modify.png"))); // NOI18N
        Alterar.setText("Alterar");
        Alterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AlterarActionPerformed(evt);
            }
        });

        tipo1.setEditable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Cancelar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Excluir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Alterar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Novo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(Salvar))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 525, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel8)
                            .addComponent(tipo1, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(valor, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tipo1)
                    .addComponent(valor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(43, 43, 43)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Alterar)
                    .addComponent(Cancelar)
                    .addComponent(Novo)
                    .addComponent(Excluir)
                    .addComponent(Salvar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void NovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NovoActionPerformed
        tipoCadastro = "novo";
        this.habilitarCampos();
    }//GEN-LAST:event_NovoActionPerformed

    private void CancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelarActionPerformed
        dispose();
        
    }//GEN-LAST:event_CancelarActionPerformed
    /**
     * Metodo que exluir um aluno do banco
     */
    private void ExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExcluirActionPerformed
        DefaultTableModel modelo = (DefaultTableModel) tabela.getModel();
        int index = tabela.getSelectedRow();
        plano = daoPlano.buscarPlano(index);
        if (Check.checkNull(plano)) {
            JOptionPane.showConfirmDialog(null, "Voce tem certeza que deseja excluir o plano selecionado?", "?", JOptionPane.YES_NO_OPTION);
            daoPlano.remove(plano);
            JOptionPane.showMessageDialog(null, "plano excluido com suscesso!");
            preencherTabela();
        } else {
            JOptionPane.showMessageDialog(this, "Erro ao Excluir!", "ERRO", JOptionPane.ERROR_MESSAGE);
        } 
    }//GEN-LAST:event_ExcluirActionPerformed
    /**
     * Metodo que salva um plano no banco, onde prenche seus respectinos dados
     * esse metodo tambem altera os dados dos planos.
     * @see metodo AlterarActionPerformed
     */
    private void SalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SalvarActionPerformed

            plano.setTipo(this.tipo1.getText());
            plano.setValor(this.valor.getText());
        if (tipoCadastro.equals("novo")) {
            daoPlano.add(plano);
            JOptionPane.showMessageDialog(null, "plano cadastrado com sucesso.", "Ok", JOptionPane.INFORMATION_MESSAGE);
        } else if (tipoCadastro.equals("alterar")) {
            daoPlano.update(plano);
            JOptionPane.showMessageDialog(null, "plano editado com sucesso.", "Ok", JOptionPane.INFORMATION_MESSAGE);
        }
        limpar();
        this.desabilitarCampos();
        this.preencherTabela();
    }//GEN-LAST:event_SalvarActionPerformed
    /**
     * Metodo que altera os dados de um plano 
     */
    private void AlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AlterarActionPerformed
  
        DefaultTableModel modelo = (DefaultTableModel) tabela.getModel();
        int index = tabela.getSelectedRow();
        plano = daoPlano.buscarPlano(index);
        this.tipo1.setText(plano.getTipo());
        this.valor.setText(plano.getValor());
        tipoCadastro = "alterar";
        habilitarCampos();
    }//GEN-LAST:event_AlterarActionPerformed
    /**
     * Metodo que desabilita os campos e botoes da tela plano
     */
     protected void desabilitarCampos() {
        tipo1.setEditable(false);
        valor.setEditable(false);
        Salvar.setEnabled(false);
    }
    /**
     * Metodo que habilita os dados da interface plano
     */
    private void habilitarCampos() {
        tipo1.setEditable(true);
        valor.setEditable(true);
        tipo1.setEditable(true);
        Salvar.setEnabled(true);
    }
    /**
     * Metodo que limpa os dados da interface plano
     */
    private void limpar(){
        tipo1.setText("");
        valor.setText("");
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PlanoView().setVisible(true);
            }
        });

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Alterar;
    private javax.swing.JButton Cancelar;
    private javax.swing.JButton Excluir;
    private javax.swing.JButton Novo;
    private javax.swing.JButton Salvar;
    private net.sf.nachocalendar.tasks.DefaultTask defaultTask1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSpinner jSpinner1;
    private javax.swing.JTable tabela;
    protected javax.swing.JTextField tipo1;
    protected javax.swing.JTextField valor;
    // End of variables declaration//GEN-END:variables
}
